#include <stdio.h>
#include <string.h>
#include <wchar.h>
#include <locale.h>
#include <errno.h>
#include "read.h"

#define BUFFER_SIZE 1024
#define BUFFER_BSIZE (BUFFER_SIZE << 2)

void _clean_text(GtkTextBuffer* buffer) {
	 gtk_text_buffer_set_text(buffer,"",0);
}

void _insert_text(GtkTextBuffer* view_buffer, const gchar* text) {
	GtkTextIter iter;
	GtkTextMark *mark;
	mark = gtk_text_buffer_get_insert(view_buffer);
	gtk_text_buffer_get_iter_at_mark(view_buffer, &iter, mark);
	gtk_text_buffer_insert(view_buffer, &iter, text, -1);
}

void _set_font() {
	PangoFontDescription *font;
	font = pango_font_description_from_string(reader->font);
	gtk_widget_modify_font(GTK_WIDGET(frame->view), font);
}

void reader_update_font(const char *font) {
	strncpy(reader->font,font,40);
	_set_font();
}

void reader_close() {
	reader->fn[0] = '\0';
	_clean_text(gtk_text_view_get_buffer(frame->view));
}

void reader_load(const char* filename) {
	if (filename != reader->fn) {
		strncpy(reader->fn, filename, FILENAME_SIZE);
	}
	//	printf("fn:%s\n", reader->fn);
	reader->fp = fopen(reader->fn, "r");
	char locale[20];
	snprintf(locale,20,"zh_CN.%s",reader->charset);
	setlocale(LC_ALL, locale);
	if (!reader->fp) {
		GtkWidget *dialog = gtk_message_dialog_new(frame->window,
				GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_ERROR,
				GTK_BUTTONS_CLOSE, "Error loading file '%s': %s", reader->fn,
				g_strerror(errno));
		gtk_dialog_run(GTK_DIALOG(dialog));
		gtk_widget_destroy(dialog);
		return;
	}
	GtkTextBuffer* view_buffer = gtk_text_view_get_buffer(frame->view);
	_clean_text(view_buffer);
	wchar_t org_buffer[BUFFER_SIZE];
	gchar text[BUFFER_BSIZE];
	while (fgetws(org_buffer, BUFFER_SIZE, reader->fp) != NULL) {
		wchar_t *buffer = org_buffer;
		setlocale(LC_ALL, "zh_CN.utf8");
		size_t n = wcsrtombs((char*)text, (const wchar_t**)&buffer,
		BUFFER_BSIZE, NULL);
		_insert_text(view_buffer,text);
		setlocale(LC_ALL, locale);
	}
	setlocale(LC_ALL, "zh_CN.utf8");
	if (ferror(reader->fp)) {
		fprintf(stderr, "read file error:%s", g_strerror(errno));
	}
	fclose(reader->fp);
	_set_font();
	theme_load();
}

void reader_reload() {
	reader_load(reader->fn);
}
